package com.lx.web;

import com.lx.entity.User;
import com.lx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller  //表示该类为控制器，负责接受请求，返回响应结果
public class UserServlet { //访问userService中的方法
    @Autowired //从spring容器中获取bean
    private UserService userService;

    //跳转到登录页面
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "/WEB-INF/jsp/logins.jsp";
    }

    //登录
    @RequestMapping("/login")
    public String login(String user_name,String password, HttpSession session){

        User user = userService.login(user_name, password);
        if (user != null){
            session.setAttribute("user",user);
            return "redirect:/bookList";
        }else {
            return "/toLogin";
        }
    }

    //跳转到注册页面
    @RequestMapping("/toRegister")
    public String toRegister(){
        return "/WEB-INF/jsp/register.jsp";
    }

    //注册
    @RequestMapping("/register")
    public String register(String user_name, String password, String real_name
            , String birthday, String phone, String address){
        User user = userService.registerUser(user_name,password,real_name,
                birthday,phone,address);
        if (user == null){
            return "/toRegister";
        }else {
            return "/toLogin";
        }
    }

    //退出登录
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        request.getSession().invalidate();
        return "redirect:/bookList";
    }
}
